﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;
using Geekees.Common.Controls;

public partial class Controls_BackEnd_NewsEdit : UserControl
{

    /// <summary>
    /// 
    /// </summary>
    private void InitializeComponent()
    {
        astvMyTree.ContextMenu.MenuItems.Add(new ASContextMenuItem("Custom Menu 1", "alert('current value:' + " + astvMyTree.ContextMenuClientID + ".getSelectedItem().parentNode.getAttribute('treeNodeValue')" + ");return false;", "otherevent"));
        astvMyTree.ContextMenu.MenuItems.Add(new ASContextMenuItem("Custom Menu 2", "alert('current text:' + " + astvMyTree.ContextMenuClientID + ".getSelectedItem().innerHTML" + ");return false;", "otherevent"));
        astvMyTree.EnableContextMenuAdd = false;
        astvMyTree.EnableContextMenuDelete = false;
        astvMyTree.EnableContextMenuEdit = false;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) return;
        InitializeComponent();
        GetData();
    }


    /// <summary>
    /// 
    /// </summary>
    private void GetData()
    {
        GenerateTree();
        News = Config.Id > 0 ? new News() { NewsID = Config.Id }.NewsGetByNewsId() : new News();
        CheckPermission();

    }


    /// <summary>
    /// 
    /// </summary>
    private void CheckPermission()
    {
        Session[SessionManager.SessionControl] = "~/Controls/Common/FileManager.ascx";
        var permission = (UserFunctions)Session[SessionManager.SessionPermission];
        btnSave.Visible = Config.Id > 0 ? permission.IsUpdate : permission.IsInsert;
        btnReset.Visible = permission.IsInsert;
        if (!permission.IsInsert && !permission.IsUpdate) return;
        txtImage.Attributes.Add("onclick", "openUpload();");
        if (string.IsNullOrEmpty(txtImage.Text))
            txtImage.Attributes.Add("value", "Click Heer To Upload.");
    }


    private string GetUrlImage()
    {
        try
        {
            var url = hdfimg.Value.ToLower();
            var link = Config.ImageUrl.ToLower();
            return url.Replace(link, string.Empty);

        }
        catch { }
        return string.Empty;
    }

    /// <summary>
    /// 
    /// </summary>
    protected News News
    {
        get
        {
            var news = (News)Session[SessionManager.SessionData] ?? new News();
            try
            {
                news.CateID = 0;// int.Parse(ddlcate.SelectedValue);
                news.Title = txtTitle.Text;
                news.TitleEn = txtTitle.Text;
                news.Summary = txtSummary.Text;
                news.Status = int.Parse(ddlStatus.SelectedValue);
                news.ImageUrl = GetUrlImage();
                news.ImageTitle = txtTitleImage.Text;
                news.Content = AjaxEditor1.Content;
                if (news.NewsID <= 0)
                    news.Author = Config.UserId;
            }
            catch { }
            return news;
        }
        set
        {
            Session[SessionManager.SessionData] = value;
            txtTitle.Text = value.Title;
            txtSummary.Text = value.Summary;
            txtTitleImage.Text = value.ImageTitle;
            AjaxEditor1.Content = value.Content;
            // ddlcate.SelectedValue = value.CateID.ToString();
            ddlStatus.SelectedValue = value.Status.ToString();
            if (string.IsNullOrEmpty(value.ImageUrl)) return;
            hdfimg.Value = Config.ImageUrl + value.ImageUrl;
            txtImage.Text = Config.ImageUrl + value.ImageUrl;
            ImgAvarta.ImageUrl = Config.ImageUrl + value.ImageUrl;
        }
    }




    /// <summary>
    /// 
    /// </summary>
    private void GenerateTree()
    {

        astvMyTree.EnableAjaxOnEditDelete = false;
        var newsCategorieses = new NewsCategories().NewsCategories_GetByCondition(string.Empty);
        Session[SessionManager.SessionList] = newsCategorieses;
        var father = newsCategorieses.FindAll(f => f.FatherID == 0);
        var chirld = newsCategorieses.FindAll(c => father.TrueForAll(f => f
                                                                          .
                                                                          FatherID !=
                                                                      c
                                                                          .
                                                                          FatherID));
        father.AddRange(chirld);
        father.Sort((f1, f2) => f1.Order.CompareTo(f2.Order));
        var dataTable = new GenericToDataTable().ConvertTo(father);
        var descripter = new ASTreeViewDataTableColumnDescriptor("Name"
                                                                  , "CateId"
                                                                  , "FatherID");
        astvMyTree.DataSourceDescriptor = descripter;
        astvMyTree.DataSource = dataTable;
        astvMyTree.DataBind();
        if (Config.Id == 0) return;
        var listpublish = new Business.NewsPublish().NewsPublish_GetByCondition("Newsid=" + Config.Id);
        foreach (var parentNode in astvMyTree.RootNode.ChildNodes)
        {
            if (listpublish.Exists(n => n.CateID == int.Parse(parentNode.NodeValue)))
                parentNode.CheckedState = ASTreeViewCheckboxState.Checked;
            SetChecked(parentNode, listpublish);
        }
    }


    private void SetChecked(ASTreeViewNode node, List<NewsPublish> list)
    {
        foreach (var subnode in node.ChildNodes)
        {
            if (list.Exists(n => n.CateID == int.Parse(subnode.NodeValue)))
                subnode.CheckedState = ASTreeViewCheckboxState.Checked;
            if (subnode.ChildNodes.Count > 0)
                SetChecked(subnode, list);
        }
    }




    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AllCommand(object sender, EventArgs e)
    {
        switch (((Control)sender).ID)
        {
            case "btnReset":
                News = new News();
                Config.Id = 0;
                break;
            case "btnBack":
                Config.Back();
                break;
            case "btnSave":
                var error = News.Save();
                if (error > 0)
                {
                    txtImage.Text = Config.ImageUrl + News.ImageUrl;
                    ImgAvarta.ImageUrl = Config.ImageUrl + News.ImageUrl;
                    News.NewsID = Config.Id = error;
                    new NewsPublish { NewsID = error }.Delete();
                    var index = 0;
                    foreach (var parentNode in astvMyTree.RootNode.ChildNodes)
                    {

                        if (parentNode.CheckedState == ASTreeViewCheckboxState.Checked)
                        {
                            new NewsPublish { NewsID = error, CateID = int.Parse(parentNode.NodeValue), Order = index, Status = (News.Status > 0 ? true : false) }.
                                Save();
                            index++;
                        }
                        SavePublish(error, parentNode);
                    }
                    Config.Message(Page, Resources.Resource.SaveSuccess, Resources.Resource.Messenger);
                    return;
                }
                switch (error)
                {
                    case -1:
                        Config.Message(Page, string.Format(Resources.Resource.ObjectExisted, Resources.Resource.Product), Resources.Resource.Warning);
                        break;
                    default:
                        Config.Message(Page, Resources.Resource.ErrorMsg, Resources.Resource.Warning);
                        break;
                }
                break;

        }

    }

    private void SavePublish(int newsid, ASTreeViewNode node)
    {
        var index = 1;
        foreach (var sub in node.ChildNodes)
        {
            if (sub.CheckedState == ASTreeViewCheckboxState.Checked)
                new NewsPublish { NewsID = newsid, CateID = int.Parse(sub.NodeValue), Order = index, Status = (News.Status > 0 ? true : false) }.
                                    Save();
            index++;
            if (sub.ChildNodes.Count > 0)
                SavePublish(newsid, sub);
        }
    }
}

